/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '')
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function findStrIndex(str, currentStr, num) {
  var x = str.indexOf(currentStr)
  for (var i = 0; i < num; i++) {
    x = str.indexOf(currentStr, x + 1)
  }
  return x
}

/**
  将base64转换为文件,接收2个参数，第一是base64，第二个是文件名字
  最后返回文件对象
*/
export function dataURLtoFile(dataurl, filename) {
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}

export function checkType(value) {
  return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}

export function getNestedValue(obj, nestedKey) {
  const keys = nestedKey.split('.');

  for (const key of keys) {
    if (obj[key] !== undefined) {
      obj = obj[key];
    } else {
      return undefined;
    }
  }

  return obj;
}

/**
 *
 * @param {string} dateTimeString
 * @returns
 */
export function convertToTimestamp(dateTimeString) {
  return dateTimeString ? new Date(dateTimeString).getTime() : 0;
}
